/**
 * 简单实现 cat 命令功能
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

#include <sys/stat.h>
#include <fcntl.h>

#define BUFF_SIZE 4096

void copy(int in_fd, int out_fd)
{
    int len;
    char buff[BUFF_SIZE];
    while (1)
    {
        len = read(in_fd, buff, BUFF_SIZE);

        if (len <= 0)
        {
            if (EINTR == errno)
            {
                continue;
            }
           // fprintf(stderr, "Read file error!\n");
            break;
        }

        write(out_fd, buff, len);
    }
}

int main(int argc, char **argv)
{
    int in_fd = STDIN_FILENO, out_fd = STDOUT_FILENO;

    int i = 1;
    for (; i < argc; ++i)
    {
        if ((in_fd = open(argv[i], O_RDONLY)) < 0)
        {
            fprintf(stderr, "Open %s file error!\n", argv[i]);
            exit(EXIT_FAILURE);
        }

        copy(in_fd, out_fd);
    }
    if(argc == 1){
        copy(in_fd, out_fd);
    }
    return 0;
}